import * as webpack from "webpack";
import { merge as mergeConfig } from "webpack-merge";
import { ConfigEnv, UserConfig, UserConfigExport } from "./types";
import webpackConfig from "./config";

export * from "./types";

const commandName = process.argv.splice(2, 1)[0];

const defineConfig = (config: UserConfigExport = {}): UserConfigExport => {
  
  if (typeof config === "function") {
    const isServe = commandName === "serve";
    const params: ConfigEnv = {
      command: isServe ? "serve" : "build",
      mode: isServe ? "development" : "production",
    };
    const { env, css, ...rest } = config(params) as UserConfig;
    return mergeConfig(webpackConfig(commandName, env, css), { ...rest });
  } else {
    const { env, css, ...rest } = config as UserConfig;
    return mergeConfig(webpackConfig(commandName, env, css), { ...rest });
  }
};

export { defineConfig, mergeConfig, webpack };
export default defineConfig;